package com.karaoke.android.kege.vm

import android.databinding.ObservableArrayList
import android.databinding.ObservableField
import android.databinding.ObservableList
import com.apkfuns.logutils.LogUtils
import com.karaoke.android.data.NetworkTools
import com.karaoke.android.data.domain.QSinger
import com.karaoke.android.data.domain.QSong
import com.karaoke.android.data.domain.Singer
import com.karaoke.android.data.domain.Song
import com.karaoke.android.data.krealmextensions.queryAll
import com.karaoke.android.data.krealmextensions.saveAll
import com.karaoke.android.data.onIO
import com.karaoke.android.data.onUI
import com.karaoke.android.data.repository.SongRepository
import com.karaoke.android.kege.BR
import com.karaoke.android.kege.OnSearchTextChangedEvent
import com.karaoke.android.kege.R
import com.karaoke.android.kege.SearchTypeChangedEvent
import com.karaoke.android.kege.adapter.SwipeGridBindingAdapter
import com.karaoke.android.library.databind.ItemBinding
import com.karaoke.android.library.mvvm.FragmentViewModel
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import rx.Observable
import rx.Subscription
import java.util.concurrent.TimeUnit

/**
 * Created by allen on 2017/4/24.
 */

class SearchAllViewModel : FragmentViewModel() {
    val qSinger = QSinger().apply { size = 120 }
    val singers = ObservableArrayList<Singer>()
    val singerBindings = ItemBinding.of<Singer>(BR.item, R.layout.search_singer_item)

    val singerTitle = ObservableField<String>().apply { set("热门歌星") }
    val songTitle = ObservableField<String>().apply { set("推荐歌曲") }


    val qSong = QSong().apply { size = 60;criteria = 0 }
    val adapter = SwipeGridBindingAdapter<Song>()
    val songs: ObservableList<Song> = ObservableArrayList<Song>()
    val songBindings: ItemBinding<Song> = ItemBinding.of<Song>(BR.viewModel, R.layout.bang_item)

    fun indexOf(s: Song) = "${songs.indexOf(s) + 1}"

    //    private var initSong: List<Song> = Song().queryAll()
    private var initSinger: List<Singer> = Singer().queryAll()
    private var initSongs: List<Song>? = null

    init {
        EventBus.getDefault().register(this)
    }

    override fun onInitLoad() {
        super.onInitLoad()
        LogUtils.e("${initSinger.size}")
        if (initSinger.isEmpty()) {
            NetworkTools.singerService.getSingers(qSinger).bindToLifecycle(this).onIO().onUI({
                it.list.saveAll()
                initSinger = it.list
                singers.addAll(initSinger)
                singerTitle.set("热门歌星")
            }, {})
        } else {
            singers.addAll(initSinger)
        }
        qSong.queryType = QSong.QueryType.QUERY_RECOMMEND
        SongRepository.getSongs(qSong).bindToLifecycle(this).onUI({ initSongs = it.list; songs.addAll(it.list) }, { it.printStackTrace() })
//        if (initSong.isEmpty())
//        {
//            qSong.queryType = QSong.QueryType.QUERY_RECOMMEND
//            SongRepository.getSongs(qSong).bindToLifecycle(this).onUI({songs.addAll(it.list)},{it.printStackTrace()})
//
////            NetworkTools.songService.getSongs(qSong).bindToLifecycle(this).onIO().map {
////                initSong = it.list
////                it.list.saveAll()
////                it.list.map(::SongItemModel)
////            }.onUI({
////                       songs.addAll(it)
////                   }, {})
//        }
//        else
//        {
//            songs.addAll(initSong.map(::SongItemModel))
//        }
        EventBus.getDefault().post(SearchTypeChangedEvent(qSong.keyword ?: ""))
    }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    private var searchSongSubscription: Subscription? = null
    private var searchSingerSubscription: Subscription? = null

    @Subscriber
    fun onSearch(e: OnSearchTextChangedEvent) {
        qSinger.searchText = e.text
        qSinger.page = 1
        singers.clear()
        if (!e.text.isNullOrEmpty()) {
            searchSingerSubscription?.unsubscribe()
            searchSingerSubscription = Observable.defer {
                NetworkTools.singerService.getSingers(qSinger)
            }.delay(200, TimeUnit.MILLISECONDS).bindToLifecycle(this).onIO().onUI({
                singers.addAll(it.list)
                singerTitle.set("搜索到的歌星  ${it.total}")
            }, {})

//            searchSingerSubscription = NetworkTools.singerService.getSingers(qSinger).bindToLifecycle(this).onIO().delay(300,TimeUnit.MILLISECONDS).onUI({
//                                                                                                                            singers.addAll(it.list)
//                                                                                                                            singerTitle.set("搜索到的歌星  ${it.total}")
//            }, {})
        } else {
            initSinger.let { singers.addAll(it); singerTitle.set("热门歌星") }
        }

        qSong.keyword = e.text
        qSong.page = 1
        qSong.queryType = QSong.QueryType.QUERY_LANGUAGE
        songs.clear()
        if (!e.text.isNullOrEmpty()) {
            searchSongSubscription?.unsubscribe()
            searchSongSubscription = Observable.defer {
                SongRepository.getSongs(qSong)
            }.delay(300, TimeUnit.MILLISECONDS).bindToLifecycle(this).onUI({ songs.addAll(it.list);songTitle.set("搜索到的歌曲  ${it.total}") }, { it.printStackTrace() })
//            searchSongSubscription = SongRepository.getSongs(qSong).bindToLifecycle(this).delay(300, TimeUnit.MILLISECONDS).onUI({ songs.addAll(it.list);songTitle.set("搜索到的歌曲  ${it.total}") }, { it.printStackTrace() })
        } else {
            initSongs?.let { songs.addAll(it) ;songTitle.set("推荐歌曲")}
//            searchSongSubscription = Observable.defer {
//                SongRepository.getSongs(qSong)
//            }.delay(300, TimeUnit.MILLISECONDS).bindToLifecycle(this).onUI({ songs.addAll(it.list);songTitle.set("推荐歌曲") }, { it.printStackTrace() })
        }
    }

}
